import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_common_app/utils/common_util/log_util.dart';
import 'custom_dialog_route.dart';
import 'loading_dialog.dart';

bool loadingStatus = false;

class LoadingController {
  final BuildContext context;

  LoadingController(this.context);

  CustomDialogRoute _customDialogRoute;

  ///显示
  void show(text) {
    if (loadingStatus) {
      return;
    }

    loadingStatus = true;

    _customDialogRoute = CustomDialogRoute(
      pageBuilder: (BuildContext context, Animation<double> animation,
          Animation<double> secondaryAnimation) {
        final Widget pageChild = Builder(builder: (BuildContext context) {
          return LoadingDialog(text);
        });
        return SafeArea(
          child: Builder(
            builder: (BuildContext context) {
              return pageChild;
            },
          ),
        );
      },
      barrierDismissible: false,
      barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
      barrierColor: Color.fromRGBO(0, 0, 0, 0.01),
      transitionDuration: const Duration(milliseconds: 150),
      transitionBuilder: _buildMaterialDialogTransitions,
    );

    Navigator.of(context, rootNavigator: true)
        .push(_customDialogRoute)
        .then((res) {
      loadingStatus = false;
    }).catchError((error) {
      LogUtil.e('show loading dialog error:$error');

      loadingStatus = false;
    });
  }

  Widget _buildMaterialDialogTransitions(
      BuildContext context,
      Animation<double> animation,
      Animation<double> secondaryAnimation,
      Widget child) {
    return FadeTransition(
      opacity: CurvedAnimation(
        parent: animation,
        curve: Curves.easeOut,
      ),
      child: child,
    );
  }

  void complete() {
    // 所有接口接口返回并有弹窗
    if (loadingStatus == true) {
      loadingStatus = false; // 修改状态

      // 完成后关闭loading窗口
      Navigator.of(context, rootNavigator: true)
          .removeRoute(_customDialogRoute);
    }
  }
}
